//
//  SpeakViewController.m
//  speakVoiceDemo
//
//  Created by kingboyrang on 2021/4/28.
//  Copyright © 2021 wulanzhou. All rights reserved.
//

#import "SpeakViewController.h"
#import "UIImage+Extension.h"
#import "ICRecordManager.h"
#import "ICVoiceHud.h"
#import "VoiceConverter.h"
#import "ICReadVoiceView.h"

#define IColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]



@interface SpeakViewController ()

/** 按住说话 */
@property (nonatomic, strong) UIButton *talkButton;
/** 录音文件名 */
@property (nonatomic,strong) NSString *recordName;
/** 记时器 */
@property (nonatomic,strong) NSTimer *timer;
/** 语音提示view */
@property (nonatomic, strong) ICVoiceHud *voiceHud;

/** 语音播放view */
@property (nonatomic, strong) ICReadVoiceView *voiceView;



@end

@implementation SpeakViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.talkButton];
    // Do any additional setup after loading the view.
}

#pragma mark -  属性
- (ICReadVoiceView *)voiceView{
    if (_voiceView == nil) {
        _voiceView = [[ICReadVoiceView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 199, 300, 199, 60)];
        //_voiceView.showDirection = VoiceShowDirectionLeft;
        //_voiceView.showDirection = VoiceShowDirectionRight;
    }
    return _voiceView;
}
//创建文件名
- (NSString *)currentRecordFileName
{
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%ld",(long)timeInterval];
    return fileName;
}

- (UIButton *) talkButton
{
    if (_talkButton == nil) {
        _talkButton = [[UIButton alloc] initWithFrame:CGRectMake(41, 200,self.view.frame.size.width - 82,49 * 0.74)];
        [_talkButton setTitle:@"按住 说话" forState:UIControlStateNormal];
        [_talkButton setTitle:@"松开 结束" forState:UIControlStateHighlighted];
        [_talkButton setTitleColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0] forState:UIControlStateNormal];
        [_talkButton setBackgroundImage:[UIImage gxz_imageWithColor:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:0.5]] forState:UIControlStateHighlighted];
        [_talkButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16.0f]];
        [_talkButton.layer setMasksToBounds:YES];
        [_talkButton.layer setCornerRadius:4.0f];
        [_talkButton.layer setBorderWidth:0.5f];
        [_talkButton.layer setBorderColor:IColor(165, 165, 165).CGColor];
        //[_talkButton setHidden:YES];
        
        //单点触摸按下事件：用户点触屏幕，或者又有新手指落下的时候。
        [_talkButton addTarget:self action:@selector(talkButtonDown:) forControlEvents:UIControlEventTouchDown];
        //所有在控件之内触摸抬起事件。
        [_talkButton addTarget:self action:@selector(talkButtonUpInside:) forControlEvents:UIControlEventTouchUpInside];
        //所有在控件之外触摸抬起事件
        [_talkButton addTarget:self action:@selector(talkButtonUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
        //所有触摸取消事件
        [_talkButton addTarget:self action:@selector(talkButtonTouchCancel:) forControlEvents:UIControlEventTouchCancel];
        //当一次触摸在控件窗口之外拖动时。
        [_talkButton addTarget:self action:@selector(talkButtonDragOutside:) forControlEvents:UIControlEventTouchDragOutside];
        //当一次触摸在控件窗口内拖动时。
        [_talkButton addTarget:self action:@selector(talkButtonDragInside:) forControlEvents:UIControlEventTouchDragInside];
    }
    return _talkButton;
}
- (ICVoiceHud *)voiceHud
{
    if (!_voiceHud) {
        _voiceHud = [[ICVoiceHud alloc] initWithFrame:CGRectMake(0, 0, 155, 155)];
        _voiceHud.hidden = YES;
        [self.view addSubview:_voiceHud];
        _voiceHud.center = CGPointMake(App_Frame_Width/2, APP_Frame_Height/2);
    }
    return _voiceHud;
}
//计时器
- (NSTimer *)timer
{
    if (!_timer) {
        _timer =[NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(progressChange) userInfo:nil repeats:YES];
    }
    return _timer;
}
//计时器事件
- (void)progressChange
{
    AVAudioRecorder *recorder = [[ICRecordManager shareManager] recorder] ;
    [recorder updateMeters];
    float power= [recorder averagePowerForChannel:0];//取得第一个通道的音频，注意音频强度范围时-160到0,声音越大power绝对值越小
    CGFloat progress = (1.0/160)*(power + 160);
    self.voiceHud.progress = progress;
}
//取消计时器
- (void)timerInvalue
{
    [_timer invalidate];
    _timer  = nil;
}



#pragma mark - voice
//语音取消
- (void)voiceDidCancelRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = YES;
}
//语音开始
- (void)voiceDidStartRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = NO;
    [self timer];
}
//语音说话过短
- (void)voiceRecordSoShort
{
    [self timerInvalue];
    self.voiceHud.animationImages = nil;
    self.voiceHud.image = [UIImage imageNamed:@"voiceShort"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.voiceHud.hidden = YES;
    });
}


#pragma mark - 按钮事件
// 说话按钮
- (void)talkButtonDown:(UIButton *)sender
{
    self.recordName = [self currentRecordFileName];

        [[ICRecordManager shareManager] startRecordingWithFileName:self.recordName completion:^(NSError *error) {
            if (error) {   // 加了录音权限的判断
            } else {
                
                //开始计时
                [self voiceDidStartRecording];
            }
        }];
}
- (void)talkButtonUpInside:(UIButton *)sender
{
    __weak typeof(self) weakSelf = self;
       [[ICRecordManager shareManager] stopRecordingWithCompletion:^(NSString *recordPath) {
           if ([recordPath isEqualToString:shortRecord]) {
               
               [weakSelf voiceRecordSoShort];
               [[ICRecordManager shareManager] removeCurrentRecordFile:weakSelf.recordName];
           } else {
               //语音说话完成 send voice message
               [weakSelf sendVoiceMessage:recordPath];
           }
       }];
}

- (void)talkButtonUpOutside:(UIButton *)sender
{

     [self voiceDidCancelRecording];
     [[ICRecordManager shareManager] removeCurrentRecordFile:self.recordName];
}

- (void)talkButtonDragOutside:(UIButton *)sender
{
    [self voiceWillDragout:NO];
}

- (void)talkButtonDragInside:(UIButton *)sender
{
    [self voiceWillDragout:YES];
}

- (void)talkButtonTouchCancel:(UIButton *)sender
{
}

// 向外或向里移动
- (void)voiceWillDragout:(BOOL)inside
{
    if (inside) {
        [_timer setFireDate:[NSDate distantPast]];
        _voiceHud.image  = [UIImage imageNamed:@"voice_1"];
    } else {
        [_timer setFireDate:[NSDate distantFuture]];
        self.voiceHud.animationImages  = nil;
        self.voiceHud.image = [UIImage imageNamed:@"cancelVoice"];
    }
}
// 语音说话完成 send voice message
- (void)sendVoiceMessage:(NSString *)voicePath
{
    [self timerInvalue]; // 销毁定时器
    self.voiceHud.hidden = YES;
    if (voicePath) {
        
        //isSender:YES
        if (![self.view.subviews containsObject:self.voiceView]) {
            [self.view addSubview:self.voiceView];
        }
        self.voiceView.voiceReadPath = voicePath;
        NSLog(@"语音说话完成 voicePath:%@",voicePath);
    }
}
@end
